package com.young.sso.controller;

import com.young.sso.common.JsonResult;
import com.young.sso.util.OssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author yang
 * @date 2022/1/11 11:46
 */
@CrossOrigin
@RestController
@Api(value = "上传文件", tags = "上传文件的接口")
public class UploadController {


    @PostMapping("/uploadToOss")
    @ApiOperation("上传单个文件到云服务器")
    public Map<String, Object> uploadToOss(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {

        //QQ截图20200724153059.png
        String originalFilename = multipartFile.getOriginalFilename();
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String suffix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        //使用UUID作为文件名,保证服务器中存放的文件名唯一
        String targetFile = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
        // 通过request获取当前程序的根路径"/"
        // 把文件直接上传到服务器的指定位置
        String fileName = "wisdomShopping/uploadImg/" + targetFile;
        // 构建文件对象
        OssUtil.upload(fileName, multipartFile.getInputStream());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("上传成功");
        jsonResult.put("fileName", targetFile);
        // jsonResult.put("fileName", "/ossLearning/" + targetFile);
        jsonResult.put("url", "http://bucket-lijianmin.oss-cn-chengdu.aliyuncs.com/" + fileName);
        return jsonResult.getDataMap();
    }


}
